package com.tanhua.sso.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.common.utils.JwtUtils;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.dubbo.api.HuanXinApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserService {

    @DubboReference(version = "1.0.0")
    private UserApi userApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RSAService rsaService;

    @DubboReference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    /**
     * 实现登录
     *
     * @param phone
     * @param code
     * @return
     */
    public Object login(String phone, String code) {
        //校验验证码是否正确
        String redisKey = "CHECK_CODE_" + phone;
        String redisCode = redisTemplate.opsForValue().get(redisKey);
        if (!StrUtil.equals(redisCode, code)) {
            return ErrorResult.builder().errCode("000001").errMessage("验证错误，请重新输入！").build();
        }
        //删除验证码
        this.redisTemplate.delete(redisKey);
        //根据手机号查询用户数据
        User user = userApi.queryByMobile(phone);
        boolean isNew = false;
        Long userId;
        if (ObjectUtil.isEmpty(user)) {
            //注册新用户
            userId = userApi.save(phone);
            isNew = true;

            //注册环信用户
            Boolean result = this.huanXinApi.register(userId);
            if (!result) {
                //注册环信失败，记录日志
                log.error("注册环信用户失败~ userId = " + user.getId());
            }
        } else {
            userId = user.getId();
        }
        //生成token
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", userId);
        String token = JwtUtils.createToken(map, rsaService.getPrivateKey(), 12);
        //发送消息
        try {
            //发送用户登录成功的消息
            HashMap<String, Object> msg = new HashMap<>();
            msg.put("id", userId);
            msg.put("date", System.currentTimeMillis());
            rocketMQTemplate.convertAndSend("tanhua-sso-login", msg);
        } catch (MessagingException e) {
            log.error("发送消息失败！", e);
        }
        HashMap<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("isNew", isNew);
        return result;
    }

    /**
     * 校验token，如果校验成功返回用户id，否则返回null
     *
     * @param token
     * @return
     */
    public Long checkToken(String token) {
        Map<String, Object> map = JwtUtils.checkToken(token, this.rsaService.getPublicKey());
        if (CollUtil.isEmpty(map)) {
            return null;
        }
        return Convert.toLong(map.get("id"));
    }

}
